import { api } from '@/utils/request'

export interface ReferredUser {
  id: string
  name: string
  idNumber: string
  registrationDate: string
}

export interface ReferralEarnings {
  yesterday: number
  today: number
  total: number
  accumulated?: number
}

export interface ReferralInfo {
  referralCode: string
  referralLink: string
  totalReferredCount: number
}

export interface ReferralEarningsData {
  earnings: ReferralEarnings
  stakingEarnings: ReferralEarnings
}

class ReferralApiService {
  /**
   * 获取推荐人信息
   */
  async getReferralInfo(): Promise<ReferralInfo> {
    try {
      const response = await api.get<ReferralInfo>('/api/referral/info')
      return response.data
    } catch (error) {
      console.error('추천 정보 조회 실패:', error)
      throw new Error('추천 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 获取推荐收益
   */
  async getReferralEarnings(): Promise<ReferralEarningsData> {
    try {
      const response = await api.get<ReferralEarningsData>('/api/referral/earnings')
      return response.data
    } catch (error) {
      console.error('추천 수익 조회 실패:', error)
      throw new Error('수익 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 获取推荐用户列表
   */
  async getReferredUsers(page: number = 1, limit: number = 20): Promise<{
    users: ReferredUser[]
    pagination: {
      page: number
      limit: number
      total: number
    }
  }> {
    try {
      const response = await api.get<{
        users: ReferredUser[]
        pagination: {
          page: number
          limit: number
          total: number
        }
      }>('/api/referral/users', {
        params: { page, limit }
      })
      return response.data
    } catch (error) {
      console.error('추천 사용자 조회 실패:', error)
      throw new Error('사용자 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 搜索推荐用户
   */
  async searchReferredUsers(query: string): Promise<ReferredUser[]> {
    try {
      const response = await api.get<ReferredUser[]>('/api/referral/search', {
        params: { query }
      })
      return response.data
    } catch (error) {
      console.error('추천 사용자 검색 실패:', error)
      throw new Error('사용자 검색에 실패했습니다')
    }
  }

  /**
   * 提交推荐收益提现申请
   */
  async submitWithdrawRequest(amountKrw: number): Promise<void> {
    try {
      await api.post<void>('/api/referral/withdraw/request', {
        amountKrw
      })
    } catch (error) {
      console.error('출금 신청 제출 실패:', error)
      throw new Error('출금 신청에 실패했습니다')
    }
  }

  /**
   * 获取推荐收益提现历史记录
   */
  async getWithdrawHistory(page: number = 1, limit: number = 20, status?: string): Promise<{
    records: any[]
    summary: any
    pagination: any
  }> {
    try {
      const response = await api.get<{
        records: any[]
        summary: any
        pagination: any
      }>('/api/referral/withdraw/history', {
        params: { page, limit, status }
      })
      return response.data
    } catch (error) {
      console.error('출금 내역 조회 실패:', error)
      throw new Error('출금 내역 조회에 실패했습니다')
    }
  }

  /**
   * 复制到剪贴板
   */
  async copyToClipboard(text: string): Promise<boolean> {
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(text)
        return true
      } else {
        const textArea = document.createElement('textarea')
        textArea.value = text
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        const result = document.execCommand('copy')
        textArea.remove()
        return result
      }
    } catch (error) {
      console.error('클립보드 복사 실패:', error)
      return false
    }
  }
}

export const referralApiService = new ReferralApiService()

// 工具函数
export const formatCurrency = (amount: number): string => {
  return new Intl.NumberFormat('ko-KR').format(amount)
}

export const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}
